﻿using System;
using System.Collections.Generic;
using System.AddIn;

namespace MabiPatch
{
	/// <summary>
	/// Description of MabiPatcher.
	/// </summary>
	[AddIn("Mabi Patcher", Version="1.0.0.0")]
	public class MabiPatcher : PowerPatcherInterop.iPlugIn
	{
	 	private Patcher _Patcher;
	 	private PowerPatcherInterop.InitInfo _info; //Store the intialization info for later use.
		private Guid _guid;
	 	
	 	public void UpdatePlugin()
		{
			//Nothing here, as the "core" plugin is updated with PP itself
		}
	 	
		public void RunPlugin()
		{
            System.Threading.Thread t = new System.Threading.Thread(()=>_Patcher.Patch());
            t.Start();
            while (t.IsAlive)
            {
            	System.Windows.Forms.Application.DoEvents();
            }
		}
	 	
		public void Initialize(PowerPatcherInterop.InitInfo info)
		{
			_info = info;
			_guid = Guid.NewGuid();
            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
            try{
            _Patcher = new Patcher(info);
            } catch (Exception ex)
            {
            	info.LogString.Invoke("ERROR: Error initializing Mabi Patcher: " + ex.Message, true);
            }
		}

        System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            if (args.Name.StartsWith("Ionic.Zip"))
            {
                byte[] b;
                using (System.IO.Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("MabiPatch.Ionic.Zip.dll"))
                {
                    b = new byte[s.Length];
                    s.Read(b, 0, (int)s.Length);
                }
                return System.Reflection.Assembly.Load(b);
            }
            else
                return null;
        }
		
		public System.Windows.Controls.UserControl GetAddInUI()
		{
			return new PatcherUI(_Patcher);
		}

        public string Name
        {
            get
            {
                return "Mabi Patcher";
            }
        }
        public Guid GetGUID()
        {
        	return _guid;
        }
    }
}